﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects;
using System.Linq;
using System.Web;
using MedicalManagementSystem.Models;
using MedicalManagementSystem.Utils;

namespace MedicalManagementSystem.Models
{
    public partial class Db
    {

        // See http://msdn.microsoft.com/en-us/library/cc716714.aspx
        // See http://blog.cincura.net/229056-onvalidate-like-validation-in-entity-framework/
        partial void OnContextCreated()
        {
            // Add saving handler
            SavingChanges += OnContextSavingChanges;
        }

        private void OnContextSavingChanges(object sender, EventArgs e)
        {
            const EntityState changedState = EntityState.Added | EntityState.Modified;

            // Validate the state of each entity in the context
            // before SaveChanges can succeed.
            foreach (var entity in
                ((ObjectContext)sender).ObjectStateManager.GetObjectStateEntries(changedState)
                    .Where(entry => (entry.Entity is IValidatable) && (!entry.IsRelationship))
                    .Select(entry => entry.Entity as IValidatable))
            {
                if (!entity.CheckBeforeSave())
                {
                    throw new RuleViolationException(entity.GetRuleViolations());
                }
            }
        }
    }

}
